package com.veer.shop.service.impl.front;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.veer.shop.config.BnBuilderConfig;
import com.veer.shop.config.Constants;
import com.veer.shop.config.OpResult;
import com.veer.shop.mapper.CustomerMapper;
import com.veer.shop.pojo.CurrentCustomerInfo;
import com.veer.shop.pojo.CustomerAdditional;
import com.veer.shop.pojo.RegisterCustomer;
import com.veer.shop.pojo.ResponseData;
import com.veer.shop.pojo.Token;
import com.veer.shop.service.front.CusomerService;
import com.veer.shop.utils.BnBuilderUtil;
import com.veer.shop.utils.EcryptUtil;
import com.veer.shop.utils.JwtUtil;
import com.veer.shop.utils.MailUtil;
import com.veer.shop.utils.PhoneUtil;
import com.veer.shop.utils.RedisUtil;
import com.veer.shop.utils.ResponseUtil;
/**
 * 客户业务处理实现类
 * 
 * @author WangBin
 * 2021年1月4日-上午10:33:18
 */
@Service
public class CustomerServiceImpl implements CusomerService {
	
	@Autowired
	private CustomerMapper customerMapper;
	@Autowired
	private BnBuilderUtil bnBuilderUtil;
	@Autowired
	private RedisUtil redisUtil;
	
	/**
	 * 会员注册
	 */
	@Override
	public ResponseData<?> register(RegisterCustomer customer) {
		// 校验注册客户参数
		OpResult<String> verify = _verifyCustomer(customer);
		if(!verify.getFlag()) {
			return ResponseUtil.error(verify.getMessage());
		}
		// 校验会员邮箱和手机号是否被使用
		if(StringUtils.isEmpty(customer.getEmail()) && customerMapper.isMailExist(customer.getEmail()) > 0) {
			return ResponseUtil.error("会员邮箱已被使用，请更换");
		}
		if(customerMapper.isPhoneExist(customer.getPhone()) >0) {
			return ResponseUtil.error("会员手机号已被使用，请更换");
		}
		// 校验验证码
		if(StringUtils.isEmpty(customer.getVerificationCode())) {
			return ResponseUtil.error("请填写验证码");
		}
		// 校验验证码是否正确 - 从 缓存中获取验证码
		String vcodeInRedis = redisUtil.get(Constants.REDIS_SUFFIX_PHONE_VCODE + customer.getPhone());
		if(!vcodeInRedis.equals(customer.getVerificationCode())) {
			return ResponseUtil.error("请填写正确的验证码");
		}
		// 删除缓存中验证码
		redisUtil.delete(Constants.REDIS_SUFFIX_PHONE_VCODE + customer.getPhone());
		
		// 会员编号
		customer.setCustomerBn(bnBuilderUtil.generate(BnBuilderConfig.BN_BUILDER_KEY_CUSTOMER));
		// 会员加密盐
		customer.setSceret(EcryptUtil.generateUUID());
		customer.setCheckedAt(customer.getCreatedAt());
		customer.setUpdatedAt(customer.getCreatedAt());
		Boolean result = _register(customer);
		if(result) {
			return ResponseUtil.success("注册成功");
		}
		return ResponseUtil.error("注册失败");
	}
	
	/**
	 * 校验注册会员参数
	 * 
	 * @param customer
	 * @return
	 */
	private OpResult<String> _verifyCustomer(RegisterCustomer customer) {
		OpResult<String> opResult = new OpResult<String>();
		// 昵称必填
		if(StringUtils.isEmpty(customer.getNickname())) {
			opResult.setMessage("请填写昵称");
		}
		// 性别必填
		if(StringUtils.isEmpty(customer.getRealname())) {
			opResult.setMessage("请填写名称");
		}
		// 邮箱非空则校验邮箱格式
		if(StringUtils.isEmpty(customer.getEmail()) && !MailUtil.verify(customer.getEmail())) {
			opResult.setMessage("请填写合法邮箱");
		}
		// 手机必填
		if(StringUtils.isEmpty(customer.getPhone())) {
			opResult.setMessage("请填写手机号");
		}
		// 手机验证码必填
		if(StringUtils.isEmpty(customer.getVerificationCode())) {
			opResult.setMessage("请填写手机验证码");
		}
		// 校验手机号格式
		if(!PhoneUtil.validPhone(customer.getPhone())) {
			opResult.setMessage("请填写合法手机号");
		}
		
		opResult.setFlag(true);
		
		return opResult;
	}
	
	/**
	 * 处理会员注册信息写入数据表
	 * 
	 * @param customer
	 * @return 
	 */
	@Transactional(rollbackFor = Exception.class)
	public Boolean _register(RegisterCustomer customer) {
		// 保存会员主表信息
		customerMapper.register(customer);
		// 保存会员信息扩展表
		CustomerAdditional customerAdditional = new CustomerAdditional();
		customerAdditional.setCustomerId(customer.getCustomerId());
		customerMapper.insertAdditional(customerAdditional);
		return true;
	}
	
	/**
	 * 获取会员的Token
	 * 
	 * @param customerId
	 * @param secret
	 * @return
	 */
	public Token getCustomerToken(Integer customerId, String secret) {
		Token token = new Token();
		String customerTokenKey = Constants.REDIS_PREFIX_CUSTOMER_TOKEN + customerId;
		String customerExpiredKey = Constants.REDIS_PREFIX_CUSTOMER_EXPIRED + customerId;
		if(redisUtil.hasKey(customerTokenKey) && redisUtil.getExpire(customerTokenKey) > 0) {
			token.setToken(redisUtil.get(customerTokenKey));
			token.setExpiredAt(Long.valueOf(redisUtil.get(customerExpiredKey)));
		} else {
			token = JwtUtil.generate(customerId, secret);
			// 存入缓存
			redisUtil.setEx(customerTokenKey, token.getToken(), Constants.JWT_TOKEN_LIFE_TIME, TimeUnit.MILLISECONDS);
			redisUtil.setEx(customerExpiredKey, String.valueOf(token.getExpiredAt()), Constants.JWT_TOKEN_LIFE_TIME, TimeUnit.MILLISECONDS);
		}
		return token;
	}
	
	/**
	 * 会员注销登录
	 * 
	 * @param currentCustomer
	 * @return
	 */
	public ResponseData<?> loginOut(CurrentCustomerInfo currentCustomer)
	{
		// 清除会员缓存token
		redisUtil.delete(Constants.REDIS_PREFIX_CUSTOMER_TOKEN + currentCustomer.getCustomerId());
		return ResponseUtil.success();
	}
}
